package com.bawei.auth.form;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.log4j.Log4j2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;

/**
 * 短信工具类
 */
@Log4j2
public class TelSmsUtils {

    /**
     * 阿里云主账号AccessKey，accessKeySecret拥有所有API的访问权限
     */
    private static String accessKeyId = "LTAI5tDyQhgVnpW8smGkdd5n";

    private static String accessKeySecret = "gsIqlRMWghdZzRPVlZWrRRnePPcJoN";

    /**
     * 短信访问域名
     */
    private static String endpoint = "dysmsapi.aliyuncs.com";
    /**
     * 短信签名
     */
    private static String signName = "乐悠购";

    private static String templateCode = "SMS_465915011";

    /**
     * 实例化短信对象
     */
    private static Client client;

    static {
        log.info("初始化短信服务开始");
        long startTime = System.currentTimeMillis();
        try {
            client = initClient();
            log.info("初始化短信成功：{}", signName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("初始化短信服务结束：耗时：{}MS", (System.currentTimeMillis() - startTime));
    }

    /**
     * 初始化短信对象
     *
     * @return
     * @throws Exception
     */
    private static Client initClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = endpoint;
        return new Client(config);
    }

    /**
     * 发送单条短信   第三方接口调用
     *
     * @param tel
     * @param sendDataMap
     */
    public static SendSmsResponseBody sendSms(String tel, Map<String, String> sendDataMap) {
        SendSmsResponse sendSmsResponse = null;
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(tel)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSONObject.toJSONString(sendDataMap));
            // 发送短信
            log.info("发送短信验证码：消息内容是：【{}】", JSONObject.toJSONString(sendDataMap));
            sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("短信发送异常，手机号：【{}】，短信内容：【{}】，异常信息：【{}】", tel, sendDataMap, e);
        }
        return sendSmsResponse.getBody();
    }

    public static boolean querySendDetails(String tel, String bizId) {
        // 3.查询结果
        QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
                .setPhoneNumber(tel)
                .setBizId(bizId)
                .setSendDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")))
                .setPageSize(10L)
                .setCurrentPage(1L);
        QuerySendDetailsResponse queryResp = null;
        try {
            queryResp = client.querySendDetails(queryReq);
        } catch (Exception e) {
            log.error("短信详情查询异常，手机号：【{}】，异常信息：【{}】", tel, e);
        }
        QuerySendDetailsResponseBody body = queryResp.getBody();
        List<QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO> dtos =
                body.getSmsSendDetailDTOs().getSmsSendDetailDTO();
        // 定义一个将字符串转换为日期的函数
        Function<String, Date> stringToDate = dateString -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 假设日期字符串的格式是"yyyy-MM-dd"
            try {
                return sdf.parse(dateString);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        };
        Optional<QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO> max = dtos.stream().max(Comparator.comparing(item -> stringToDate.apply(item.getSendDate())));
        QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO querySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO = max.get();
        // 打印结果
        return querySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO.getSendStatus() == 3;
    }


}
